package com.example.arithmeticleetcode.learnArithmetic.quque.circle;

import java.util.Arrays;

/**
 * @program: arithmetic-leetcode
 * @description: 循环双端队列
 * @author: FangZhen
 * @create: 2020-08-24 15:14
 **/
public class CircleDeque<E> {

    private int front;

    private int size;

    private E[] elements;

    private static final int DEFAULT_CAPACITY = 10;

    public CircleDeque() {
        elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void clear() {
        size = 0;
        for (int i = 0; i < size; i ++) {
            elements[index(i)] = null;
        }
        front = 0;
    }

    /**
     * 从尾部入队
     *
     * @param element
     */
    public void enQuqueRear(E element) {
        ensureCapacity(size + 1);
        elements[index(size)] = element;
        size ++;
    }

    /**
     * 从头部出队
     *
     * @return
     */
    public E deQuqueFront() {
        E element = elements[front];
        elements[front] = null;
        front = index(1);
        size --;
        return element;
    }

    /**
     * 从头部入队
     *
     * @param element
     */
    public void enQuqueFront(E element) {
        ensureCapacity(size + 1);
        front = index(-1);
        elements[front] = element;
        size ++;
    }

    /**
     * 从尾部出队
     *
     * @return
     */
    public E deQuqueRear() {
        E element = elements[index(size - 1)];
        elements[index(size - 1)] = null;
        size --;
        return element;
    }

    /**
     * 获取头部数据
     *
     * @return
     */
    public E front() {
        return elements[front];
    }

    /**
     * 获取尾部数据
     *
     * @return
     */
    public E rear() {
        return elements[index(size - 1)];
    }

    private int index(int index) {
        index += front;
        if (index < 0) {
            return index + elements.length;
        }
        return index % elements.length;
    }

    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) return;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[index(i)];
        }
        elements = newElements;

        front = 0;
    }

    @Override
    public String toString() {
        return "CircleDeque{" +
                "front=" + front +
                ", size=" + size +
                ", elements=" + Arrays.toString(elements) +
                '}';
    }
}
